﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using System.Text;
using System.IO;
using System.Dynamic;
using FluorineFx.Json;

namespace lxwmvc
{
    /// <summary>
    /// 投标
    /// </summary>
    public static partial class huifucontroller
    {

        /// <summary>
        /// 发起投标
        /// </summary>
        /// <param name="pb"></param>
        [json]
        [trans]
        public static void huifu_toubiao(pagebase pb)
        {
            //没有模板
            string strSql = "";
            DataTable dt_jisuan = new DataTable();
            int pjkjbxxid = pb.v_i("pjkjbxxid");//借款id
            decimal tzjine = pb.v_dec("tzjine");//投资金额
            pb.ifcheck(tzjine<=0, "您的投资金额超过标的可投金额！");


            string yhids = pb.v_s("yhids");//选中的优惠ids
            decimal tzjine_yh = pb.v_dec("yhamount");//来自账户优惠与红包的金额

            string userid = core_user.userID;
            string zongjine = string.Empty;
            string dongjieyue = string.Empty;

            //得到用户真实的账户余额
            decimal tzjine_yue = huifu_chaxun_yue(userid, out zongjine, out dongjieyue, false)
                .todecimal();//来自汇付余额的金额（Update By 冀兴光）

            //获取标的信息
            supermodel biaoinfo = supermodel.create("pjkjbxx")
                .where("pjkjbxxid=" + pjkjbxxid)
                .get();

            //可投金额
            decimal touzizongjine = supermodel.create("pjktzjl")
                .select(" SUM(toubiaojine)")
                .where("zhuangtai='正常' AND pjkjbxxid=" + pjkjbxxid)
                .one<decimal>();

            decimal jiekuanjine = biaoinfo["jiekuanjine"].todecimal();

            pb.ifcheck((touzizongjine + tzjine) > jiekuanjine, "您的投资金额超过标的可投金额！");
            pb.ifcheck(tzjine - tzjine_yh > tzjine_yue, "账户余额不足！");

            var zhuangtai = biaoinfo["zhuangtai"].toint32();
            pb.ifcheck(zhuangtai != 3 && zhuangtai != 4, "当前阶段不允许投资！");            

            //if (P2PHelper.IsInLingTouZu(GlobalString.LOGIN_USER_PRIV))//领投人
            //{
            //    if (tzjine.todecimal() + biaoinfo["yitoujine"].todecimal() > biaoinfo["jiekuanjine"].todecimal())//投标总额超过借款金额不允许
            //    {
            //        PropertyBag["jiekuanjine"] = biaoinfo["jiekuanjine"].todecimal();
            //        jshelper.alert("投标总额不得超过剩余可投资金额:" + (biaoinfo["jiekuanjine"].todecimal() - biaoinfo["yitoujine"].todecimal()) + "！");
            //        return;
            //    }
            //    strSql = " select * from dbo.pjkjbxx  where pjkjbxxid=" + pjkjbxxid;
            //    DataTable dt = jiandansql.gettable(strSql);
            //    if (dt != null)
            //    {
            //        if (dt.Rows[0]["biaodileixing"].ToString() == "转债权")
            //        {
            //            shengchengzhaiquantouzijilu(pjkjbxxid, HttpContext.Current.Session["g_user_id"].ToString(), tzjine);
            //        }
            //        else
            //        {
            //            shengchengtouzijilu(pjkjbxxid, yhids, HttpContext.Current.Session["g_user_id"].ToString(), tzjine, tzjine_yh);
            //        }
            //    }

            //}
            //else
            {
                pb.ifcheck(zhuangtai != 4, "当前状态不允许投资！");

                //投标总额超过借款金额不允许
                pb.ifcheck(tzjine.todecimal() + biaoinfo["yitoujine"].todecimal() > biaoinfo["jiekuanjine"].todecimal(),"投标总额不得超过借款金额！");

                if (biaoinfo["biaodileixing"].ToString() == "转债权")
                {
                    //生成债券投资记录
                    huifu_toubiao_shengchengzhaiquantouzijilu(biaoinfo, core_user.userID, tzjine);
                }
                else
                {
                    //生成投资记录
                    huifu_toubiao_shengchengtouzijilu(biaoinfo, yhids, core_user.userID, tzjine, tzjine_yh);
                }
            }
        }

        /// <summary>
        /// 保存投资记录
        /// </summary>
        /// <param name="pjkjbxxid"></param>
        /// <param name="yhids"></param>
        /// <param name="touzirenid"></param>
        /// <param name="tzjine"></param>
        /// <param name="tzjineyh"></param>
        static void huifu_toubiao_shengchengtouzijilu(supermodel biaoinfo , string yhids, string touzirenid, decimal tzjine, decimal tzjineyh)
        {
            supermodel userinfo = core_user.getUserInfo(touzirenid);
            var pjkjbxxid = biaoinfo.get<int>("pjkjbxxid"); 
            //生成借款投资记录
            int pjktzjlid = queryhelper.get("insert into pjktzjl(pjkjbxxid,toubiaorenid,toubiaojine,youxiaojine,toubiaoshijian,zhuangtai) values(" + pjkjbxxid + ",'" + touzirenid + "'," + tzjine.tostr() + "," + tzjineyh.tostr() + ",GETDATE(),'未支付');select @@identity").toint32();

            #region 生成投资人收益计划 By:lxw
            //年化
            decimal rate = biaoinfo["nianlilv"].todecimal();
            //期限
            int mouth = biaoinfo.get<int>("qixian"); 
            //放款方式
            int huankuanfangshi = biaoinfo.get<int>("huankuanfangshi");
            //返款时间
            DateTime datetime = biaoinfo.get<DateTime>("fangkuanshijian");

            //计算还款计划（每个投资人单独计算）
            IList<PBenefitPlan> plans = core_p2p.GetBenefitPlansByInvestmentAmount(pjktzjlid, pjkjbxxid, touzirenid, tzjine, tzjineyh, rate / 100, mouth, huankuanfangshi, datetime);

            if (plans != null && plans.Count > 0)
            {
                string sqlStr = string.Empty;
                for (int i = 0; i < plans.Count; i++)
                {
                    sqlStr = string.Format(" INSERT INTO PBenefitPlan VALUES ({0},'{1}',{2},{3},'{4}',{5},{6}) ", plans[i].ProjectID, plans[i].UserID, plans[i].Principal, plans[i].Interest, plans[i].Deadline.ToShortDateString(), -1, plans[i].phkid);
                    queryhelper.execute(sqlStr);
                }
            }
            #endregion
            //主动投标记录
            //跟汇付接口连接。

            InitiativeTender objsend = new InitiativeTender();
            ////订单ID，日期+流水号，补齐6位长度
            //objsend.OrdId = DateTime.Now.ToString("yyyyMMdd") + pjktzjlid.ToString().PadLeft(6, '0');
            //objsend.OrdDate = DateTime.Now.ToString("yyyyMMdd");

            //todo 投资金额,必须保留两位小数
            //Update By JXG 投资金额减去优惠金额
            decimal transAmount = tzjine - tzjineyh;
            objsend.TransAmt = transAmount.ToString("#0.00");

            //todo 投资人，通过sysuser_kuozhan中的UsrCustId 读取
            objsend.UsrCustId = userinfo["UsrCustId"] + "";

            //最大投资手续费率，固定位0.1 测试环境取值范围 0.01<= MaxTenderRate<=0.2 正式  0.01<= MaxTenderRate<=0.2
            objsend.MaxTenderRate = HuiFuArg.MaxTenderRate;
            //获取借款人信息
            //DataRow row = jiandansql.getonerow("select * from pjkjbxx where pjkjbxxid=" + pjkjbxxid);
            //todo 借款人UsrCustId
            var jiekuanren_UsrCustId = core_user.getUsrCustId(biaoinfo["jiekuanrenid"]+"");
                //jiandansql.getstring("select UsrCustId from sysuser_kuozhan where user_id='" + row["jiekuanrenid"].tostr() + "'");

            //todo 这个是标的利率 必须两位小数
            //var jiekuanren_BorrowerRate = Convert.ToDouble(row["nianlilv"].tostr()).ToString("0.00");
            //最大值
            var jiekuanren_BorrowerRate = "1.00";
            
            //BorrowerCustId 借款人
            objsend.BorrowerDetails = ("[{\"BorrowerCustId\":\"" + jiekuanren_UsrCustId + "\",\"BorrowerAmt\":\"" + objsend.TransAmt + "\",\"BorrowerRate\":\"" + jiekuanren_BorrowerRate + "\"}]");
            //proid 不能传递,传递项目ID会出现错误。
            //,\"ProId\":\"" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + "\"
            //BorrowerRate 手续费+利率

            //下面四个参数不用传递
            //objsend.BorrowerCustId = "";
            //objsend.BorrowerAmt = "";
            //objsend.BorrowerRate = "";
            //objsend.ProId = "";

            //这个地方必须设置成Y。冻结用户资金
            objsend.IsFreeze = "Y";

            //冻结单号跟订单号一致。
            //objsend.FreezeOrdId = objsend.OrdId;

            //后台通知页面
            objsend.BgRetUrl = HuiFuArg.LocalUrl + "huifu/huifu_toubiao_returnbg";
            //通知页面
            objsend.RetUrl = HuiFuArg.LocalUrl + "huifu/huifu_toubiao_return";

            //todo 这里需要插入一条到投资流水表里面。对应的表为 Mmanualbid 表里面。
            supermodel data = supermodel.create("Mmanualbid");
            //todo.start 补充完整里面的信息
            data["User_Id"] = core_user.userID;
            data["SetupDate"] = DateTime.Now;
            data["OrdId"] = objsend.OrdId + "";
            data["OrdDate"] = objsend.OrdDate + "";//订单日期
            data["TransAmt"] = objsend.TransAmt + "";
            data["UsrCustId"] = objsend.UsrCustId + ""; //用户号
            data["MaxTenderRate"] = objsend.MaxTenderRate + ""; //最大投资手续费率      
            data["IsFreeze"] = objsend.IsFreeze + "";//是否冻结
            data["FreezeOrdId"] = objsend.FreezeOrdId + "";//冻结单号

            //这里面的信息一定要补充全了，后面需要用着
            data["BorrowerCustId"] = jiekuanren_UsrCustId;
            data["BorrowerAmt"] = objsend.TransAmt;
            data["BorrowerRate"] = jiekuanren_BorrowerRate;

            //todo 投资对应的产品ID，需要正确配置
            data["proid"] = pjkjbxxid.tostr();

            //lxw 20141108 添加.s
            data["touzhijiluid"] = pjktzjlid.tostr();
            data["maxid"] = requesthelper.getonevalue("maxid");
            //lxw 20141108 添加.e

            //0 是代表为处理 1是代表成功 2代表失败
            data["logtype"] = "0";
            //todo.end 补充完整里面的信息
            if (yhids != "") //判断是否使用优惠券
            {
                data["yhids"] = yhids;
                data["AcctId"] = HuiFuArg.AcctId;
                data["VocherAmt"] = objsend.TransAmt + "";

                //没有走汇付，就是这部分资金也不要存在。

                //objsend.ReqExt = "{\"Vocher\":{\"AcctId\":\"" + ConfigurationManager.AppSettings["AcctId"].tostr() + "\",\"VocherAmt\":\"" + objsend.TransAmt + "\"}}";
            }
            //得到插入的主键
            var ret = data.saveorupdate();

            //插入成功后，把流水的ID传递到实体中
            objsend.MerPriv = ret.identity + "";

            core_huifu.Submit(objsend);
        }


        /// <summary>
        /// todo  这个页面主要是汇付返回页面
        /// </summary>
        [trans]
        public static void huifu_toubiao_return(pagebase pb)
        {
            //最好锁住
            try
            {                
                RetInitiativeTender objrev = new RetInitiativeTender();
                //后台调用，最终要打印出来参数
                core_huifu.ReturnUrl(HttpContext.Current, "OrdId", objrev, false);


                if (objrev.RespCode == core_huifu.HUIFU_SUCCESS)
                {
                    huifu_toubiao_return_funx(objrev);
                    //JSHelper.Redirect("/PUser/message.html?status=1&msg=InitiativeTender");
                }
                else
                {
                    //JSHelper.Redirect("/PUser/message.html?status=0&msg=InitiativeTender&code=" + objrev.RespCode);
                }
            }
            catch (Exception e)
            {
                dataloger.fatal("error:",e);

            }
        }

        /// <summary>
        /// 锁定汇付返回的方法
        /// </summary>
        public static readonly object[] _syn = new object[0] { };
        /// <summary>
        /// 锁定这个方法
        /// </summary>
        /// <param name="objrev"></param>
        static void huifu_toubiao_return_funx(RetInitiativeTender objrev)
        {
            lock (_syn)
            {
                huitu_toubiao_updatezhuangtai(objrev);

                //投资汇付操作流水
                supermodel touziliushui = supermodel.create("Mmanualbid")
                                            .where("Mmanualbidid=" + objrev.MerPriv)
                                            .get();

                //借款投资记录
                var pjktzjl = supermodel.create("pjktzjl")
                    .where(" pjktzjlid=" + touziliushui["touzhijiluid"])
                    .get();

                if (pjktzjl["zhuangtai"].tostr() == "未支付")
                {
                    var pjkjbxxid = touziliushui["proid"];
                    
                    //获取借款基本信息
                    supermodel jkjbxx = supermodel.create("pjkjbxx")
                                            .where("pjkjbxxid=" + pjkjbxxid)
                                            .get();

                    var yitoujine = jkjbxx.get<decimal>("yitoujine");
                    var jiekuanjine = jkjbxx.get<decimal>("jiekuanjine");
                    var toubiaojine = pjktzjl.get<decimal>("toubiaojine");
                    string jiekuanbiaoti = jkjbxx.get<string>("jiekuanbiaoti");

                    var yitoujine_db = supermodel.create("pjktzjl")
                        .select("SUM(toubiaojine)")
                        .where("pjkjbxxid=" + pjkjbxxid + " AND (zhuangtai='正常' or zhaungtai='线下')")
                        .one<Decimal>();

                    if (yitoujine != yitoujine_db)//传入的已投金额与数据库中已投金额不一致 
                    {
                        //没有做任何处理，把数据库最新的金额进行更新
                        yitoujine = yitoujine_db;
                    }
                    else if (toubiaojine + yitoujine > jiekuanjine)//投资金额超过借款金额  
                    {
                        //这里应该就是超标了？？？
                        pjktzjl.set("zhuangtai", "超额投标").update();
                    }
                    else//正常投资
                    {
                        pjktzjl.set("zhuangtai", "正常").update();

                        //已投金额是回来的时候判断的。
                        jkjbxx.set("yitoujine", toubiaojine + yitoujine).update();
                        
                        //更新可投金额
                        queryhelper.execute(" update pjkjbxx set ketoujine=(jiekuanjine-yitoujine) where pjkjbxxid=" + pjkjbxxid);

                        //是否使用了优化
                        if (touziliushui.get<string>("yhids").tostr() != "")
                            supermodel.create("user_youhui")
                                .set("zhuangtai", "已使用")
                                .set("InvestmentID", 0)
                                .where("user_youhuid in (" + touziliushui["yhids"] + ")")
                                .update();

                    }

                    //更新这笔投资的还款计划状态
                    supermodel.create("PBenefitPlan")
                        .set("PlanStatus", 0)
                        .where("pjktzjlid=" + touziliushui["touzhijiluid"])
                        .update();

                    //代表该标已经投满
                    if (toubiaojine + yitoujine >= jiekuanjine)
                    {
                        ////判断转让后是否满标更新标的状态为回款完毕
                        jkjbxx.set("zhuangtai", 5).update();
                    }

                    //发送短信
                    string MOBIL_NO = core_user.getMobileByUserId(touziliushui["User_Id"] + "");
                    //SMSApp.SendMsg(MOBIL_NO, "亲爱的嘉金投资用户,您于" + DateTime.Now.ToString("F") + "成功投资 “" + jiekuanbiaoti + "” 您的投资共计人民币￥" + dr["TransAmt"].tostr() + "元已被冻结直至招标结束，请静候招标结果。若非本人操作，请您联系致电客服。400-100-0616");
                    //发送站内信
                    core_user.sendMessage(touziliushui["User_Id"].tostr(), "亲爱的嘉金投资用户,您于" + DateTime.Now.ToString("F") + "成功投资 “" + jiekuanbiaoti + "” 您的投资共计人民币￥" + touziliushui["TransAmt"].tostr() + "元已被冻结直至投标结束，请静候投标结果。若非本人操作，请您联系致电客服。400-100-0616");
                }
            }            
        }

        /// <summary>
        /// todo  这个页面主要是汇付返回页面 后台打印的方法
        /// </summary>
        public static void huifu_toubiao_returnbg(pagebase pb)
        {
            try
            {
                RetInitiativeTender objrev = new RetInitiativeTender();
                //后台调用，最终要打印出来参数
                core_huifu.ReturnUrl(HttpContext.Current, "OrdId", objrev, true);

                if (objrev.RespCode == core_huifu.HUIFU_SUCCESS)
                {
                    huifu_toubiao_return_funx(objrev);
                }
            }
            catch (Exception e)
            {
                dataloger.fatal("huifu_toubiao_returnbg", e);
            }
        }

        //todo 这里主要是处理投标流水
        static void huitu_toubiao_updatezhuangtai(RetInitiativeTender objrev)
        {
            try
            {
                supermodel Mmanualbid = supermodel.create("Mmanualbid");
                //返回原来投标记录的主键
                Mmanualbid["Mmanualbidid"] = objrev.MerPriv + "";
                Mmanualbid["FreezeTrxId"] = objrev.FreezeTrxId;
                Mmanualbid["TrxId"] = objrev.TrxId;
                //代表投资记录成功，这里完全可以模仿开户，前面检查这笔投标是否成功，成功就自动跳转。
                Mmanualbid["logtype"] = "1";
                Mmanualbid["MerCustId"] = objrev.MerCustId + "";//商户号 
                //更新信息
                Mmanualbid.saveorupdate();

                

            }
            catch (Exception e)
            {
                dataloger.fatal("huitu_toubiao_updatezhuangtai", e);
            }
        }
    }
}